using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

public class AudioManager : Singleton<AudioManager>
{
    // 保存音效路径和音效文件
    private Dictionary<string, AudioClip> sourceManagerDic = new Dictionary<string, AudioClip>();
    
    /// <summary>
    /// 获取音效文件位置
    /// </summary>
    /// <param name="loadPathSFX"></param>
    /// <returns></returns>
    private AudioClip GetAudioClipSFX(string loadPathSFX)
    {
        // 检测字典当中有没有
        if(!sourceManagerDic.ContainsKey(loadPathSFX))
        {
            // 没有就添加
            sourceManagerDic.Add(loadPathSFX, (AudioClip)Resources.Load(loadPathSFX));
        }
        return sourceManagerDic[loadPathSFX];
    }

    /// <summary>
    /// BGM播放
    /// </summary>
    /// <param name="loadPathBGM">BGM加载路径</param>
    public void PlayerAudioSourceBGM(string loadPathBGM, AudioSource audioSource)
    {
        audioSource = Camera.main.GetComponent<AudioSource>();
        audioSource.Pause();
        audioSource.clip = Resources.Load<AudioClip>(loadPathBGM);
        audioSource.volume = AudioVolume.Instance.GetAudioVolumeBGM();
        audioSource.Play();
    }

    /// <summary>
    /// 使用对象池音效播放
    /// </summary>
    /// <param name="loadPathSFX">音效路径 储存在常量中</param>
    /// <param name="parentObj">父物体，将音效物体挂载上去</param>
    public void PlayAudioSourceSFX(string loadPathSFX, GameObject parentObj)
    {
        AudioSource audioSource = GenericsObjectPoolManager<AudioSource>.Instance.CreateObject(parentObj.name, parentObj);
        audioSource.GetComponent<Transform>().gameObject.SetActive(true);
        audioSource.clip = GetAudioClipSFX(loadPathSFX);
        audioSource.volume = AudioVolume.Instance.GetAudioVolumeSFX();
        audioSource.Play();
        Replace(parentObj.name, audioSource, 0.5f);
    }

    /// <summary>
    /// 不使用对象池的音效播放
    /// </summary>
    /// <param name="loadPathSFX">音效路径 储存在常量中</param>
    /// <param name="audioSource">播放音效的组件</param>
    public void PlayAudioSourceSFX(string loadPathSFX, AudioSource audioSource)
    {
        audioSource.clip = GetAudioClipSFX(loadPathSFX);
        audioSource.volume = AudioVolume.Instance.GetAudioVolumeSFX();
        audioSource.Play();
    }
    
    // 异步编程，延迟0.5秒执行
    async void Replace(string parentObjName, AudioSource audioSource, float delayTime)
    {
        // 等待音效播放完成
        // while (audioSource.isPlaying){}
        
        // 异步编程  延迟函数
        await Task.Delay(Mathf.RoundToInt(delayTime * 1000));

        // 音效播放完成后的操作
        GenericsObjectPoolManager<AudioSource>.Instance.AddObjectPool(parentObjName, audioSource);
        audioSource.GetComponent<Transform>().gameObject.SetActive(false);
    }
}



